package seller_service

import (
	"fmt"
	"github.com/gin-gonic/gin"
	jsoniter "github.com/json-iterator/go"
	"go.uber.org/zap"
	"math/big"
	"math/rand"
	"strconv"
	"strings"
	"time"
	"wwt-gin-api/app/global/request"
	"wwt-gin-api/app/global/response"
	"wwt-gin-api/app/global/utils"
	"wwt-gin-api/app/global/variable"
	"wwt-gin-api/app/model/api_model"
	"wwt-gin-api/app/service/merchant_user_info"
	"wwt-gin-api/app/service/sys_brokerage_base"
	"wwt-gin-api/app/utils/cur_userinfo"
	"wwt-gin-api/app/utils/redis_factory"
)

func SellerServiceFactory() *SellerService {
	return &SellerService{}
}

type SellerService struct {
}

//OrdinaryPush 发布任务
func (receiver *SellerService) OrdinaryPush(ctx *gin.Context, req *request.OrderReq) *response.OrdinaryPushResp {
	userInfo := cur_userinfo.GetUserInfoByToken(ctx)
	redisClient := redis_factory.GetOneRedisClient()
	defer redisClient.ReleaseOneRedisClient()
	lockKey := fmt.Sprintf("ordinaryPush:%d", userInfo.Id)
	expirationTime := time.Now().Add(1 * time.Minute)
	lockValue := "locked"
	checkLock, _ := redisClient.String(redisClient.Execute("GET", lockKey))
	if checkLock == lockValue {
		return &response.OrdinaryPushResp{
			Code:    0,
			Message: "抱歉，请勿重复提交",
		}
	}
	_, _ = redisClient.String(redisClient.Execute("SETNX", lockKey, lockValue))
	_, _ = redisClient.Execute("expireAt", lockKey, expirationTime.Unix())
	defer func() {
		//删除锁
		_, _ = redisClient.Execute("DEL", lockKey)
	}()
	//查询是否暂停商家放单
	open, err := redisClient.Bool(redisClient.Execute("hGet", "setting:permission_switch", "merchantOrders"))
	if err != nil {
		variable.ZapLog.Error("redis获取错误", zap.Error(err))
	}
	if open == false {
		return &response.OrdinaryPushResp{
			Code:    0,
			Message: "抱歉，系统正在维护，请稍后再试",
		}
	}
	// 判断定时时间是否是之前的时间
	if req.Timing.Switch == "1" {
		pushTime, _ := time.ParseInLocation("2006-01-02 15:04", req.Timing.Time, time.Local)
		if pushTime.Before(time.Now()) {
			return &response.OrdinaryPushResp{
				Code:    400,
				Message: "定时时间不能小于当前时间",
			}
		}
	}
	if req.TaskRequire.IsChecKeword {
		// 判断taskRequire.checkewordAnswer是否在taskRequire.checKewordFull中
		if req.TaskRequire.ChecKewordFull != "" && !strings.Contains(req.TaskRequire.ChecKewordFull, req.TaskRequire.CheckewordAnswer) {
			return &response.OrdinaryPushResp{
				Code:    400,
				Message: "关键词答案不正确",
			}
		}
	}
	//一、计算商品价格,含副商品
	goodsTotalPriceTotal := receiver.GoodsTotalPrice(req.GoodsData, req.TaskRequire)
	if goodsTotalPriceTotal > 2000 {
		return &response.OrdinaryPushResp{
			Code:    0,
			Message: "商品总价格不能超过2000元",
		}
	}
	if goodsTotalPriceTotal < 0 {
		return &response.OrdinaryPushResp{
			Code:    0,
			Message: "商品价格错误",
		}
	}
	//商家需支付的基本服务费
	sellerServicePrice := float64(0)
	//买手获得的基本服务费
	buyerServicePrice := float64(0)
	//代理获得的基本推广费
	proxyCommission := float64(0)
	servicePriceInfo := receiver.BaseServicePrice(userInfo, req, goodsTotalPriceTotal)
	if servicePriceInfo != nil {
		sellerF, _ := strconv.ParseFloat(servicePriceInfo.Seller, 64)
		sellerServicePrice = sellerF
		buyerF, _ := strconv.ParseFloat(servicePriceInfo.Buyer, 64)
		buyerServicePrice = buyerF
		proxyF, _ := strconv.ParseFloat(servicePriceInfo.Proxy, 64)
		proxyCommission = proxyF
	}
	if sellerServicePrice == 0 || buyerServicePrice == 0 {
		return &response.OrdinaryPushResp{
			Code:    0,
			Message: "系统繁忙，请稍后再试",
		}
	}
	//商家需支付的增值费,买手获得的增值费,代理获得的增值费
	sellerExpend, buyerExpend, proxyExpend, detailsOfExpenses := receiver.AccretionServicePrice("1", req.UseAccretionFeeList, req)
	proxyCommissionTotal1 := new(big.Float).Add(big.NewFloat(proxyCommission), big.NewFloat(proxyExpend))
	proxyCommissionTotal, _ := proxyCommissionTotal1.Float64()
	commission1 := new(big.Float).Add(big.NewFloat(buyerServicePrice), big.NewFloat(buyerExpend))
	commission, _ := commission1.Float64()
	// 计算商家支出总费用,如果是商返，只计算佣金*任务数量
	sellerTotalPrice := new(big.Float).SetPrec(64)
	sellerTotalPrice.Add(big.NewFloat(goodsTotalPriceTotal), big.NewFloat(sellerServicePrice))
	sellerTotalPrice.Add(sellerTotalPrice, big.NewFloat(sellerExpend))
	taskNumF := big.NewFloat(float64(req.TaskNum))
	sellerTotalPrice.Mul(sellerTotalPrice, taskNumF)
	//商家单订单只需支付
	subtractBalance, _ := sellerTotalPrice.Float64()
	if req.RefundMethod == "merchant" {
		subtractBalance1 := new(big.Float).Add(big.NewFloat(sellerServicePrice), big.NewFloat(sellerExpend))
		subtractBalance1.Mul(subtractBalance1, big.NewFloat(float64(req.TaskNum)))
		subtractBalance, _ = subtractBalance1.Float64()
	}
	merchantFactory := merchant_user_info.CreateMerchantUserInfoCurdFactory()
	merchantInfo := merchantFactory.GetOne(map[string]interface{}{
		"username": userInfo.Username,
	}, "id,balance")
	if merchantInfo.Balance < subtractBalance {
		return &response.OrdinaryPushResp{
			Code:    0,
			Message: "余额不足，请充值",
		}
	}
	//计算师傅和上级师傅的提成
	oneBuyerTaskReward, secondBuyerTaskReward := receiver.CommissionPrice(0)
	//计算平台收益
	platformEarningsF := new(big.Float).Sub(
		new(big.Float).Sub(
			new(big.Float).Sub(
				new(big.Float).Sub(
					new(big.Float).Sub(
						new(big.Float).SetFloat64(sellerServicePrice),
						new(big.Float).SetFloat64(sellerExpend),
					),
					new(big.Float).SetFloat64(commission),
				),
				new(big.Float).SetFloat64(oneBuyerTaskReward),
			),
			new(big.Float).SetFloat64(secondBuyerTaskReward),
		),
		new(big.Float).SetFloat64(proxyCommissionTotal),
	)
	platformEarnings, _ := platformEarningsF.Float64()
	timingArr := receiver.GetTimingArr2(req.TaskNum, req.Timing)
	taskId := generateTaskID()
	detailsOfExpensesJson, _ := jsoniter.MarshalToString(detailsOfExpenses)
	refundMethod := "1"
	if req.RefundMethod == "platform" {
		refundMethod = "0"
	}
	taskState := "0"
	if req.Timing.Switch == "1" || req.Timing.Interval.Value > 0 {
		taskState = "4"
	}
	timingSwitch := req.Timing.Switch
	pushTime := time.Now()
	if timingSwitch == "1" {
		pushTime, _ = time.ParseInLocation("2006-01-02 15:04", req.Timing.Time, time.Local)
	}
	taskListModel := api_model.CreateTaskListFactory("")
	taskListModel.DB.Create(&api_model.TaskList{
		Tid:                 taskId,
		ShopId:              req.ShopId,                                                      // 商家绑定的店铺，不是链接店铺id
		MerchantId:          int32(userInfo.Id),                                              // 商家id
		Terminal:            req.Terminal,                                                    //下单终端
		Type:                "1",                                                             // 默认成交单
		Platform:            req.Platform,                                                    //默认淘宝/天猫
		PlaceOrderPrice:     goodsTotalPriceTotal,                                            // 商品最终价格（折扣后）含副宝贝价格
		ActualPayment:       subtractBalance,                                                 // 商家实际支付金额
		OrderCount:          float64(req.GoodsData.OrderNum),                                 // 每个单子的下单数量
		TaskCount:           req.TaskNum,                                                     // 订单数量，循环单数
		AdditionPriceTotal:  receiver.AffiliatedProductPrice(req.GoodsData, req.TaskRequire), //副宝贝总价
		BaseServicePrice:    sellerServicePrice,                                              // 商家支付的单个订单基础服务费
		AccretionPriceTotal: sellerExpend,                                                    // 增值服务费
		Content:             req.Body,                                                        //任务要求
		UseAccretionDetail:  detailsOfExpensesJson,
		MoneyRefundMethod:   refundMethod,
		TaskState:           taskState,
		IntervalTime:        int32(req.Timing.Interval.Value),
		PushTime:            pushTime,
	})
	// 判断是不是用关键词，如果是关键词则根据关键词单量创建订单，否则根据任务数量创建订单
	// 根据关键词单量放单
	if req.EnterTheStoreWay.Method == "searchKeyword" {
		indexTemp := 1
		for index, item := range req.PlaceOrderKeyWordWay {
			for i := 1; i < item.OrderQuantity; i++ {
				OrderId := receiver.generateOrderID(taskId, indexTemp)
				useAccretionFeeListStr, _ := jsoniter.MarshalToString(req.UseAccretionFeeList)
				itemStr, _ := jsoniter.MarshalToString(item)
				orderContent, _ := jsoniter.MarshalToString(map[string]interface{}{
					"goodsData":         req.GoodsData,
					"orderPlaceType":    req.OrderPlaceType,
					"orderPlaceEntry":   req.OrderPlaceEntry,
					"orderPlaceDelay":   req.OrderPlaceDelay,
					"enterTheStoreWay":  req.EnterTheStoreWay,
					"placeOrderkeyWord": itemStr,
					"taskRequire":       req.TaskRequire,
				})
				//礼品代发编码
				giftCode := ""
				if req.ExpressService.Switch == "1" {
					giftCode = req.ExpressService.Gift
				}
				isMerchantRefund := "1"
				if req.RefundMethod == "platform" {
					isMerchantRefund = "0"
				}
				// 定时为暂停 订单状态 -1等待接单 -2暂停 0取消 1已接单 2已找到 3已付款 4已发货 5已收货 6 已完成
				state := -1
				isTiming := "0"
				if req.Timing.Switch == "1" || req.Timing.Interval.Value > 0 {
					state = -3
					isTiming = "1"
				}
				orderModel := &api_model.TaskOrder{
					Tid:                    taskId,
					OrderId:                OrderId,
					Platform:               req.Platform,         //平台
					UnitPrice:              goodsTotalPriceTotal, //本金
					Commission:             commission,           //买手佣金
					MerchantId:             int32(userInfo.Id),
					OrderContent:           orderContent,
					MainGoodsTitle:         req.GoodsData.GoodsName,
					UseAccretionFeeList:    useAccretionFeeListStr,
					GiftCode:               giftCode,
					BUpperCommission:       oneBuyerTaskReward,    //一级师傅佣金
					BUpperUpCommission:     secondBuyerTaskReward, //二级师傅佣金
					AgentPromotionExpenses: proxyCommissionTotal,  //代理佣金
					PlatformEarnings:       platformEarnings,      //平台收益
					State:                  int8(state),
					IsMerchantRefund:       isMerchantRefund,
					IsMerchantCheck:        req.TaskRequire.IsMerchantCheck, //是否需要商家审核
					IsTiming:               isTiming,
					PushTime:               timingArr[0],
					CreateTime:             time.Now(),
				}
				taskOrderModel := api_model.CreateTaskOrderFactory("")
				taskOrderModel.DB.Create(&orderModel)
				// 如果是定时订单，则不添加放单池
				if isTiming == "0" {
					go func() {
						receiver.AddTaskToCache(req.Platform, OrderId, req.TaskRequire, userInfo.Id)
					}()
				}
				indexTemp++
			}
			indexTemp += index
		}
	} else {
		for i := 1; i <= req.TaskNum; i++ {
			OrderId := receiver.generateOrderID(taskId, i)
			useAccretionFeeListStr, _ := jsoniter.MarshalToString(req.UseAccretionFeeList)
			itemStr, _ := jsoniter.MarshalToString(req.PlaceOrderKeyWordWay)
			orderContent, _ := jsoniter.MarshalToString(map[string]interface{}{
				"goodsData":         req.GoodsData,
				"orderPlaceType":    req.OrderPlaceType,
				"orderPlaceEntry":   req.OrderPlaceEntry,
				"orderPlaceDelay":   req.OrderPlaceDelay,
				"enterTheStoreWay":  req.EnterTheStoreWay,
				"placeOrderkeyWord": itemStr,
				"taskRequire":       req.TaskRequire,
			})
			//礼品代发编码
			giftCode := ""
			if req.ExpressService.Switch == "1" {
				giftCode = req.ExpressService.Gift
			}
			isMerchantRefund := "1"
			if req.RefundMethod == "platform" {
				isMerchantRefund = "0"
			}
			// 定时为暂停 订单状态 -1等待接单 -2暂停 0取消 1已接单 2已找到 3已付款 4已发货 5已收货 6 已完成
			state := -1
			isTiming := "0"
			if req.Timing.Switch == "1" || req.Timing.Interval.Value > 0 {
				state = -3
				isTiming = "1"
			}
			orderModel := &api_model.TaskOrder{
				Tid:                    taskId,
				OrderId:                OrderId,
				Platform:               req.Platform,         //平台
				UnitPrice:              goodsTotalPriceTotal, //本金
				Commission:             commission,           //买手佣金
				MerchantId:             int32(userInfo.Id),
				OrderContent:           orderContent,
				MainGoodsTitle:         req.GoodsData.GoodsName,
				UseAccretionFeeList:    useAccretionFeeListStr,
				GiftCode:               giftCode,
				BUpperCommission:       oneBuyerTaskReward,    //一级师傅佣金
				BUpperUpCommission:     secondBuyerTaskReward, //二级师傅佣金
				AgentPromotionExpenses: proxyCommissionTotal,  //代理佣金
				PlatformEarnings:       platformEarnings,      //平台收益
				State:                  int8(state),
				IsMerchantRefund:       isMerchantRefund,
				IsMerchantCheck:        req.TaskRequire.IsMerchantCheck, //是否需要商家审核
				IsTiming:               isTiming,
				PushTime:               timingArr[0],
			}
			taskOrderModel := api_model.CreateTaskOrderFactory("")
			taskOrderModel.DB.Create(&orderModel)
			// 如果是定时订单，则不添加放单池
			if isTiming == "0" {
				go func() {
					receiver.AddTaskToCache(req.Platform, OrderId, req.TaskRequire, userInfo.Id)
				}()
			}
		}
	}
	// 对商家余额进行扣款
	//转换成负数
	subtractBalanceF := 0 - subtractBalance
	errM := merchant_user_info.CreateMerchantUserInfoCurdFactory().AddMerchantBalanceLog(userInfo.Username, subtractBalanceF, &request.LogReq{
		Source:  2,
		Remark:  "发布任务",
		OrderSn: taskId,
	})
	if errM != nil {
		return &response.OrdinaryPushResp{
			Code:    1018,
			Message: errM.Error(),
		}
	}
	// 平台增加预收
	refundStr := "本金+佣金"
	if req.RefundMethod == "merchant" {
		refundStr = "佣金"
	}
	remark := userInfo.Username + "发布任务】，扣除商家" + refundStr
	errP := SellerLogServiceFactory().AddPlatformBalanceLog(subtractBalanceF, &request.LogReq{
		Source:  66,
		Remark:  remark,
		OrderSn: taskId,
	})
	if errP != nil {
		return &response.OrdinaryPushResp{
			Code:    1018,
			Message: errP.Error(),
		}
	}
	return &response.OrdinaryPushResp{
		Code:    200,
		Message: "成功",
	}
}

func (receiver *SellerService) AddTaskToCache(platform, orderID string, taskRequire request.TaskRequire, merchantID int) {
	redisClient := redis_factory.GetOneRedisClient()
	defer redisClient.ReleaseOneRedisClient()
	addTaskQueue, err := receiver.AddTaskQueue(redisClient, platform, orderID, taskRequire, merchantID)
	if err != nil {
		variable.ZapLog.Error("AddTaskToCache-redis任务入队失败", zap.Error(err))
		return
	}
	_, err2 := redisClient.Int64(redisClient.Execute("hset", "Order:"+platform, orderID, addTaskQueue))
	if err2 != nil {
		variable.ZapLog.Error("AddTaskToCache-hset-redis失败", zap.Error(err2))
	}
	return
}

// AddTaskQueue 添加任务进redis消息队列
func (receiver *SellerService) AddTaskQueue(redisClient *redis_factory.RedisClient, platform, orderID string, taskRequire request.TaskRequire, merchantID int) (string, error) {
	taskMap := make(map[string]interface{})
	tqStr, _ := jsoniter.MarshalToString(taskRequire)
	_ = jsoniter.UnmarshalFromString(tqStr, &taskMap)
	taskMap["merchant_id"] = merchantID
	taskMap["platform"] = platform
	taskJSON, err := jsoniter.Marshal(taskMap)
	if err != nil {
		return "", err
	}
	if redisClient == nil {
		redisClient = redis_factory.GetOneRedisClient()
		defer redisClient.ReleaseOneRedisClient()
	}
	target, err2 := redisClient.String(redisClient.Execute("XADD", "TASK:"+platform, "*", orderID, taskJSON))
	if err2 != nil {
		variable.ZapLog.Error("redis任务入队失败", zap.Error(err2))
	}
	return target, err
}

func (receiver *SellerService) generateOrderID(taskID string, indexTemp int) string {
	indexTempStr := strconv.Itoa(indexTemp)
	orderID := strings.Replace(taskID, "T", "D", 1) + "-" + indexTempStr
	return orderID
}

func (receiver *SellerService) AffiliatedProductPrice(goodsData request.GoodsData, taskRequire request.TaskRequire) float64 {
	if taskRequire.IsAffiliatedProduct == "1" && len(goodsData.AffiliatedProduct) > 0 {
		var AffiliatedProductPrice float64
		for _, product := range goodsData.AffiliatedProduct {
			AffiliatedProductPrice += product.Price
		}
		return AffiliatedProductPrice
	}
	return 0
}

// GoodsTotalPrice
//@param {*} goodsData 商品数据
//@param {*} isAffiliatedProduct 是否携带副商品
func (receiver *SellerService) GoodsTotalPrice(goodsData request.GoodsData, taskRequire request.TaskRequire) float64 {
	AffProductPrice := receiver.AffiliatedProductPrice(goodsData, taskRequire)
	price, _ := new(big.Float).Add(new(big.Float).SetFloat64(goodsData.UnitPrice), new(big.Float).SetFloat64(AffProductPrice)).Float64()

	switch goodsData.Discount.Method {
	case "discount":
		disCount, _ := strconv.ParseFloat(goodsData.Discount.Value, 64)
		price, _ = new(big.Float).Mul(new(big.Float).Mul(new(big.Float).SetFloat64(price), new(big.Float).SetInt64(int64(goodsData.OrderNum))), new(big.Float).Quo(new(big.Float).SetFloat64(disCount), new(big.Float).SetFloat64(100))).Float64()
	case "coupon":
		couponMoney, _ := strconv.ParseFloat(goodsData.Discount.CouponMoney, 64)
		price, _ = new(big.Float).Sub(new(big.Float).Mul(new(big.Float).SetFloat64(price), new(big.Float).SetInt64(int64(goodsData.OrderNum))), new(big.Float).SetFloat64(couponMoney)).Float64()
	case "changePrice":
		price = float64(goodsData.Discount.ChangePrice)
	case "fullReduction":
		fullReductionMoney, _ := strconv.ParseFloat(goodsData.Discount.FullReductionMoney, 64)
		price, _ = new(big.Float).Sub(new(big.Float).Mul(new(big.Float).SetFloat64(price), new(big.Float).SetInt64(int64(goodsData.OrderNum))), new(big.Float).SetFloat64(fullReductionMoney)).Float64()
	default:
		price, _ = new(big.Float).Mul(new(big.Float).SetFloat64(price), new(big.Float).SetInt64(int64(goodsData.OrderNum))).Float64()
	}

	return price
}

// BaseServicePrice 计算基础服务费
//@param {*} platform 平台
//@param {*} level 商家等级
//@param {*} goodsTotalPrice 商品总价
func (receiver *SellerService) BaseServicePrice(userInfo *response.UserInfo, req *request.OrderReq, goodsTotalPriceTotal float64) *api_model.SysBrokerageBase {
	merchantFactory := merchant_user_info.CreateMerchantUserInfoCurdFactory()
	merchantInfo := merchantFactory.GetOne(map[string]interface{}{
		"username": userInfo.Username,
	}, "id,level")
	levelStr := strconv.Itoa(int(merchantInfo.Level))
	sysBrokerageBaseKey := fmt.Sprintf("setting:sys_brokerage_base:%s:%s", req.Platform, levelStr)
	redisClient := redis_factory.GetOneRedisClient()
	defer redisClient.ReleaseOneRedisClient()
	sysBrokerageBase, err2 := redisClient.String(redisClient.Execute("get", sysBrokerageBaseKey))
	if err2 != nil {
		variable.ZapLog.Error("redis获取错误-sysBrokerageBase", zap.Error(err2))
		return nil
	}
	sysBrokerageBaseValue := make([]*api_model.SysBrokerageBase, 0)
	if sysBrokerageBase == "" {
		sysBase := sys_brokerage_base.CreateSysBrokerageBaseCurdFactory()
		sysBrokerageBaseValue = sysBase.GetAll(map[string]interface{}{
			"shop_value": req.Platform,
			"level_id":   userInfo.Level,
		}, "")
	} else {
		err := jsoniter.Unmarshal([]byte(sysBrokerageBase), &sysBrokerageBaseValue)
		if err != nil {
			variable.ZapLog.Error("解析错误-sysBrokerageBase", zap.Error(err2))
			return nil
		}
	}
	basePriceInfo := &api_model.SysBrokerageBase{}
	for _, val := range sysBrokerageBaseValue {
		pMax, _ := strconv.ParseFloat(val.PriceMax, 64)
		pMin, _ := strconv.ParseFloat(val.PriceMin, 64)
		if goodsTotalPriceTotal <= pMax && goodsTotalPriceTotal >= pMin {
			basePriceInfo = val
		}
	}
	return basePriceInfo
}

// AccretionServicePrice
//* 计算增值服务费,返回商家与买手的费用
//* @param {*} type
//* @param {*} keys
func (receiver *SellerService) AccretionServicePrice(sType string, useAccretionFeeList []string, req *request.OrderReq) (float64, float64, float64, []*response.DetailsOfExpensesResp) {
	redisClient := redis_factory.GetOneRedisClient()
	defer redisClient.ReleaseOneRedisClient()
	if len(useAccretionFeeList) == 0 {
		return 0, 0, 0, nil
	}
	sysBrokerageAccretionJson, _ := redisClient.String(redisClient.Execute("get", "setting:sys_brokerage_adjun"))
	//if err2 != nil {
	//	variable.ZapLog.Error("redis获取错误-accretionServicePrice", zap.Error(err2))
	//	return 0, 0, 0, nil
	//}
	sysBrokerageAccretion := make([]*api_model.SysBrokerageAdjun, 0)
	accretionPriceInfoArr := make([]*api_model.SysBrokerageAdjun, 0)
	_ = jsoniter.UnmarshalFromString(sysBrokerageAccretionJson, &sysBrokerageAccretion)
	for _, sysBrokerage := range sysBrokerageAccretion {
		if sysBrokerage.TaskType == sType && sysBrokerage.State == "0" && utils.Contains(useAccretionFeeList, sysBrokerage.Key) {
			accretionPriceInfoArr = append(accretionPriceInfoArr, sysBrokerage)
		}
	}
	sellerExpend := big.NewFloat(0)
	buyerExpend := big.NewFloat(0)
	proxyExpend := big.NewFloat(0)
	for _, cur := range accretionPriceInfoArr {
		// 如果是副宝贝，则按副宝贝数量*增值费价格
		if cur.Key == "isAffiliatedProduct" {
			bCost := new(big.Float)
			bCost.SetString(cur.Bcost)
			affiliatedProductLength := len(req.GoodsData.AffiliatedProduct)
			sellerExpend.Add(sellerExpend, new(big.Float).Mul(bCost, big.NewFloat(float64(affiliatedProductLength))))
			sCost := new(big.Float)
			sCost.SetString(cur.Scost)
			buyerExpend.Add(buyerExpend, new(big.Float).Mul(sCost, big.NewFloat(float64(affiliatedProductLength))))
			pCost := new(big.Float)
			pCost.SetString(cur.Pcost)
			proxyExpend.Add(proxyExpend, new(big.Float).Mul(pCost, big.NewFloat(float64(affiliatedProductLength))))
		} else {
			bCost := new(big.Float)
			bCost.SetString(cur.Bcost)
			sellerExpend.Add(sellerExpend, bCost)
			sCost := new(big.Float)
			sCost.SetString(cur.Scost)
			buyerExpend.Add(buyerExpend, sCost)
			pCost := new(big.Float)
			pCost.SetString(cur.Pcost)
			proxyExpend.Add(proxyExpend, pCost)
		}
	}
	detailsOfExpenses := make([]*response.DetailsOfExpensesResp, 0, len(accretionPriceInfoArr))
	for _, accretionPriceInfo := range accretionPriceInfoArr {
		item := &response.DetailsOfExpensesResp{
			Key:   accretionPriceInfo.Key,
			BCost: accretionPriceInfo.Bcost,
			SCost: accretionPriceInfo.Scost,
			PCost: accretionPriceInfo.Pcost,
		}
		detailsOfExpenses = append(detailsOfExpenses, item)
	}
	sellerExpendFloat64, _ := sellerExpend.Float64()
	buyerExpendFloat64, _ := buyerExpend.Float64()
	proxyExpendFloat64, _ := proxyExpend.Float64()
	return sellerExpendFloat64, buyerExpendFloat64, proxyExpendFloat64, detailsOfExpenses
}

// CommissionPrice 计算师傅和上级师傅的佣金,如果用到百分比，则需要计算百分比
func (receiver *SellerService) CommissionPrice(totalCommission float64) (float64, float64) {
	redisClient := redis_factory.GetOneRedisClient()
	defer redisClient.ReleaseOneRedisClient()
	spreadConfStr, _ := redisClient.String(redisClient.Execute("get", "setting:spread_conf"))
	spreadConf := response.SpreadConf2Resp{}
	_ = jsoniter.UnmarshalFromString(spreadConfStr, &spreadConf)
	if spreadConf.RewardType == 1 {
		totalCommissionF := new(big.Float).SetFloat64(totalCommission)
		oneBuyerTaskReward := new(big.Float).SetFloat64(spreadConf.OneBuyerTaskReward)
		secondBuyerTaskReward := new(big.Float).SetFloat64(spreadConf.SecondBuyerTaskReward)
		oneBuyerTaskReward = new(big.Float).Quo(new(big.Float).Mul(totalCommissionF, oneBuyerTaskReward), new(big.Float).SetFloat64(100.0))
		secondBuyerTaskReward = new(big.Float).Quo(new(big.Float).Mul(totalCommissionF, secondBuyerTaskReward), new(big.Float).SetFloat64(100.0))
		oneBuyerTaskRewardFloat64, _ := oneBuyerTaskReward.Float64()
		secondBuyerTaskRewardFloat64, _ := secondBuyerTaskReward.Float64()
		return oneBuyerTaskRewardFloat64, secondBuyerTaskRewardFloat64
	}
	return spreadConf.OneBuyerTaskReward, spreadConf.SecondBuyerTaskReward
}

// GetTimingArr2 返回定时时间列表2
//taskNum 任务数量
//timing 定时时间
func (receiver *SellerService) GetTimingArr2(taskNum int, timing request.Timing) []string {
	pushTimeArr := make([]string, 0)
	switchVal := timing.Switch
	timeVal := timing.Time
	intervalVal := timing.Interval

	for i := 1; i <= taskNum; i++ {
		var pushTime time.Time
		if switchVal == "1" && timeVal != "" {
			parsedTime, _ := time.ParseInLocation("2006-01-02 15:04", timeVal, time.Local)
			pushTime = parsedTime
		} else {
			pushTime = time.Now()
		}

		intervalValue := intervalVal.Value
		intervalType := intervalVal.Type

		if intervalValue != 0 && intervalType != "" {
			pushTime = pushTime.Add(time.Duration((i-1)*intervalValue) * getIntervalDuration(intervalType))
		}

		pushTimeArr = append(pushTimeArr, pushTime.Format("2006-01-02 15:04"))
	}

	return pushTimeArr
}

func getIntervalDuration(intervalType string) time.Duration {
	switch intervalType {
	case "minute":
		return time.Minute
	case "hour":
		return time.Hour
	case "day":
		return 24 * time.Hour
	case "week":
		return 7 * 24 * time.Hour
	default:
		return time.Duration(0)
	}
}

//生成任务id
func generateTaskID() string {
	timestamp := time.Now().UnixNano() / int64(time.Millisecond)
	randomStr := createNonceStrings(2)
	taskID := fmt.Sprintf("T%d%s", timestamp%1000000, randomStr)
	return taskID
}

func createNonceStrings(length int) string {
	const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	nonceStr := make([]byte, length)
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < length; i++ {
		nonceStr[i] = charset[rand.Intn(len(charset))]
	}
	return string(nonceStr)
}
